package com.daykw.wenshu.task;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.daykw.wenshu.config.NutzDaoConfig;
import com.daykw.wenshu.http.HttpBase;
import com.daykw.wenshu.model.CaseText;
import com.daykw.wenshu.model.CourtUrl;
import com.daykw.wenshu.utils.SpringContextHolder;
import com.daykw.wenshu.utils.TQueue;

public class ArticleHtmlJob extends Thread {

	private static Logger logger = Logger.getLogger(ArticleHtmlJob.class);
	private static final java.util.Random RANDOM = new java.util.Random();

	@Override
	public void run() {

		while (true) {
			try {
				CourtUrl info = TQueue.getAQueue().take();
				this.doWork(info);
			} catch (Exception e) {
				logger.error("", e);
			}
		}

	}

	public void doWork(CourtUrl task) {

		HttpBase http = new HttpBase();
		Map<String, String> headers = new HashMap<String, String>();
		NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
		int c = dao.count(CaseText.class, Cnd.where("doc_id", "=", task.getDoc_id()));
		if (c > 0) {
			dao.update(CourtUrl.class, Chain.make("handled", "A"), Cnd.where("doc_id", "=", task.getDoc_id()));
			return;
		}

		headers.put("User-Agent",
				"Mozilla/5.0 (Windows NT " + (RANDOM.nextInt(5) + 1) + ".1) AppleWebKit/" + (RANDOM.nextInt(537) + 1)
						+ "." + (RANDOM.nextInt(11) + 1) + " (KHTML, like Gecko) Chrome/" + (RANDOM.nextInt(23) + 1)
						+ ".0." + (RANDOM.nextInt(1271) + 1) + "." + (RANDOM.nextInt(95) + 1) + " Safari/"
						+ (RANDOM.nextInt(537) + 1) + "." + (RANDOM.nextInt(11) + 1) + "");
		try {
			String url = "http://wenshu.court.gov.cn/CreateContentJS/CreateContentJS.aspx?DocID=" + task.getDoc_id();
			// String url =
			// "http://wenshu.court.gov.cn/CreateContentJS/CreateContentJS.aspx?DocID=d5122c6c-e739-425d-a698-a9750033e180&KeyWord=";
			String html = http.fget(url, headers, true);
			while (html == null || html.equals("fail")) {

				html = http.fget(url, headers, true);
				if (html != null && !html.equals("fail")) {
					break;
				}

			}
			if (html.equals("400") || html.equals("404") || html.equals("500") || html.equals("502")) {

				return;
			}
			String[] rows = html.split("\r\n");
			for (String row : rows) {
				if (row.contains("此篇文书不存在!")) {
					String date = df.format(new Date());
					String content = "此篇文书不存在!";
					long size = content.length();
					CaseText caset = new CaseText();

					caset.setTxt(content);
					caset.setTxt_len(size);
					caset.setDoc_id(task.getDoc_id());
					caset.setIs_deleted("Y");
					caset.setSource(0);
					caset.setHtml(content);
					caset.setCreate_date(Integer.parseInt(date));
					caset.setCreate_time(new Date());
					try {
						dao.fastInsert(caset);
						dao.update(CourtUrl.class, Chain.make("handled", "A").add("update_time", new Date()),
								Cnd.where("doc_id", "=", task.getDoc_id()));
					} catch (Exception e) {
						logger.error(e.getMessage());

					}

					logger.info(task.getDoc_id() + "下載完成,任务队列剩余:" + TQueue.getAQueue().size() + "#####");
					break;
				} else if (row.contains("var jsonHtmlData =")) {
					String json = row.replace("var jsonHtmlData =", "");
					json = json.substring(0, json.length() - 1);
					json = json.trim();
					json = json.substring(0, json.length() - 1);
					json = json.substring(0 + 1, json.length());
					json = json.replace("\\", "");
			
					JSONObject j = JSON.parseObject(json);
				
					String ht = j.getString("Html");
					Document doc = Jsoup.parse(ht);
					String content = this.getContent(doc.html());

					
					
				
					String date = df.format(new Date());
					content = task.getCase_name() + "_|__|_" + content;
					long size = content.length();
					CaseText caset = new CaseText();
					caset.setHtml(doc.html());
					caset.setTxt(content);
					caset.setTxt_len(size);
					caset.setDoc_id(task.getDoc_id());
					caset.setIs_deleted("N");
					caset.setSource(0);
					caset.setCreate_date(Integer.parseInt(date));
					caset.setCreate_time(new Date());
					try {
						dao.fastInsert(caset);
						dao.update(CourtUrl.class, Chain.make("handled", "A").add("update_time", new Date()),
								Cnd.where("doc_id", "=", task.getDoc_id()));
					} catch (Exception e) {
						logger.error(e.getMessage());

					}

					logger.info(task.getDoc_id() + "下載完成,任务队列剩余:" + TQueue.getAQueue().size() + "#####");
					break;

				}
			}

		} catch (Exception e) {
			logger.error("", e);
		}

	}
	private String getContent(String html) {
		String content = html.replace("\\", "");
		String cc = "";
		if (content.indexOf("<pstyle") >= 0 || content.indexOf("<spanstyle") >= 0 || content.indexOf("<pclass") >= 0
				|| content.indexOf("<palign") >= 0 || content.indexOf("<spanlang") >= 0) {
			content = content.replace("<pstyle", "<p style");
			content = content.replace("<spanstyle", "<span style");
			content = content.replace("<pclass", "<p class");
			content = content.replace("<palign", "<p align");
			content = content.replace("<spanlang", "<span lang");
			content = content.replace("”", "'");
			Document doc = Jsoup.parse(content);

			List<Element> tn = doc.getElementsByTag("p");
			for (Element tt : tn) {

				cc = cc + tt.text() + "_|_";
			}
			cc = cc.replace("\r\n", "_|_");
		} else {
			content = content.replace("”", "'");
			Document doc = Jsoup.parse(content);

			List<Element> tn = doc.getElementsByTag("div");
			for (Element tt : tn) {

				cc = cc + tt.text() + "_|_";
			}
			cc = cc.replace("\r\n", "_|_");

		}
		cc = cc.replace("p t ” >", "");
		return cc;
	}
}
